/**
 * 牛牛
 * @author Troj.an
 */
class NNGameSceneViewNew extends V.GameView
{
    // 控件
    public gameBg: eui.Image;
    public table: eui.Image;
    public bgArea: eui.Rect;
    public menuButton: how.Button;
    public gameIdLabel: how.Label;
    public players: eui.Group;
    public playerView0: NNPlayerView;
    public playerView1: NNPlayerView;
    public playerView2: NNPlayerView;
    public playerView3: NNPlayerView;
    public gameEffectPanel: NNGameEffectPanel;
    public backMenuGroup: eui.Group;
    public backButton: how.Button;
    public settingBtn: how.Button;
    public cardTypeButton: how.Button;
    public gameRecord: how.Button;
    public operateCardGroup: eui.Group;
    public youniuBtn: how.Button;
    public meiniuBtn: how.Button;
    public helpButton: how.Button;
    public pipeiTip: eui.Group;
    public messageLabel: how.Label;
    public resumeGame: how.Button;
    public numImg: eui.Image;
    public progressTimerGroup: eui.Group;
    public progressTimerLabel: eui.BitmapLabel;
    public fightCardLabel0: how.Label;
    public fightCardLabel1: how.Label;
    public fightCardLabel2: how.Label;
    public fightCardLabel3: how.Label;
    public tipImg: eui.Image;
    public cardTypeGroup: eui.Group;
    public pinpaicuowu: how.Animation;
    public tip0Group: eui.Group;
    public tip1Group: eui.Group;
    public tip2Group: eui.Group;
    public zhidaoBtn: how.Button;
    // public lastIndex = null;
    // public data: NNGameSceneData = NNGameSceneData.getInstance();
    public nn_deng: eui.Image;

    // 变量
    public intervalNumber: number = null;
    public addScoreData: any;//加注数据
    public cbCardData: Array<number> = []; // 自己的手牌
    public cbAllCardData: any = null; // 所有玩家的牌
    public onCardList: Array<any> = [];//选中牌的列表
    public onCardListCount: number = 0;//选中牌的总数
    public valueEffect: number = 0;//定庄动画值
    public playerCardsXList: Array<Array<number>> = [];
    public static AllowReportChildren: Array<any> = ["NNGameEffectPanel"];
    private gameStatusTimer = null;
    public bankerSeat: number = 0;  // 庄家座位
    public effectPlayers: Array<any> = [];
    public gameEndData: any = null;
    public lGameScore: any = 0;
    public gameEndCardData: any = null;
    public alert: any = null;
    public dailog: any = null;

    private nn_myCardType = 
    {
        10: 28,
        11: 19,
        12: 19,
        13: 17,
        14: 31
    }

     public constructor() 
     {
        super();
        this.MAX_PLAYER = 4;
        this.skinName = "NNGameSceneSkin";
        this.Res = DataConfig.ResConfig[DataConfig.KIND_ID_NN];
    }

    protected childrenCreated(): void 
    {
        this.initGameView();
        how.SoundManager.playMusic("nn_bg_mp3");
        this.initPlayer();
        this.backButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onBackButton, this);
        this.bgArea.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchGroup, this);
        this.settingBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onSettingBtn, this);
        this.menuButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onMenuButton, this);
        this.cardTypeButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onCardTypeButton, this);
        this.youniuBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onYouniuBtn, this);
        this.meiniuBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onMeiniuBtn, this);
        this.gameRecord.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onGameRecord, this);
        this.helpButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onHelpButton, this);
        this.zhidaoBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onZhidaoBtn, this);
        for (var i = 0; i < 5; i++) 
        {
            this["card" + i].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onCard, this);
        }
        for (var j = 0; j < 3; j++) 
        {
            this["p0addScoreBtn" + j].addEventListener(egret.TouchEvent.TOUCH_TAP, this.onAddScoreAreaBtn, this);
        }
        this.gameEffectPanel.gameView = this;
        this.tip0Group.visible = false;
        this.tip1Group.visible = false;
        this.tip2Group.visible = false;
        this.showBreatheLight();
    }
    
    /** 收到网络消息 */
    public onNetData(s:number, d:any):void
    {
        switch(s)
        {
            case 100: // 游戏开始
            {
                this.initGameView();

                this.gameStatusTimer = egret.setTimeout(this.startProgressTimer, this, 2000, [8]);
                this.bankerSeat = this.c2p(d.wBankerUser);
                this.gameEffectPanel.playGameAnimation("nn_deal_{0}_png", 33);
                how.SoundManager.playEffect("nn_gamestart_mp3");
                for(var i = 0; i < this.MAX_PLAYER; i++)
                {
                    this.playerList[i].onGameStart(d);
                }
                // 显示开始加注
                this.startAddScore(d);
                break;
            }
            case 103: // 收到发牌
            {
                this.cbAllCardData = d.cbCardData;
                for (var i = 0; i < this.MAX_PLAYER; i++) 
                {
                    var player: NNPlayerView = this["player" + i]
                    if(player.getData())
                    {
                        this.gameEffectPanel.playCardEffect(i, this.cbAllCardData[player.chairId]);
                    }
                }
                how.SoundManager.playEffect("nn_sendcard_mp3");
                // 设置时钟
                egret.clearTimeout(this.gameStatusTimer);
                this.startProgressTimer(20);
                break;
            }
            case 105: // 牛牛比牌
            {
                // var gameData = (this.data as NNGameSceneData);
                var seatID = this.c2p(d.wPlayerID);
                this.openCard({
                    wPlayerChairID: d.wPlayerID,
                    cbCardData: this.cbAllCardData[d.wPlayerID],
                    CardType: NNCardLogic.getCardType(this.cbAllCardData[d.wPlayerID]),
                    bOpen: 1
                    });
                var gender = this["player" + seatID].getData().gender == 1 ? "malecow_" : "femalecow_";
                var openCardData = {
                    cbCardData:this.cbAllCardData[d.wPlayerID],
                    CardType:d.CardType,
                    mp3Source:gender + d.CardType + "_mp3",
                };
                // this.callUI("showPlayerCard", seatID, openCardData);
                this.showPlayerCard(seatID, openCardData);
                break;
            }
            case 104: // 游戏结束
            {
                console.log(">>> NNGameSceneModule onNNGameEnd!!!");
                this.lGameScore = d.lGameScore;
                this.gameEndCardData = d.cbCardData;
                this.onGameEnd(d);
                for (var i = 0; i < this.MAX_PLAYER; i++)
                {
                    let pv:NNPlayerView = <NNPlayerView>this.playerList[i];
                    if(pv.getData())
                    {
                        pv.onGameEnd(d);
                    }
                }
                egret.Tween.get(this).wait(1000).call(this.gameEndEffectComplet, this);
                egret.Tween.get(this).wait(6000).call(this.gameEndInitView, this);
                break;
            }
        }
    }

        //当游戏结束
    public onGameEnd(data: any): void 
    {
        console.log(">>> NNGameSceneView onGameEnd");
        this.tip1Group.visible = false;
        this.tip2Group.visible = false;
        this.tipImg.visible = false;
        this.operateCardGroup.visible = false;
        this.stopProgressTimer();
    }

    //停止倒计时
    public stopProgressTimer(): void 
    {
        egret.Tween.removeTweens(this.progressTimerLabel);
        this.progressTimerGroup.visible = false;
    }

        //播放结算和翻牌动画
    public gameEndEffectComplet(): void 
    {
        this.tipImg.visible = false;
        this.operateCardGroup.visible = false;
        // var gameData = NNGameSceneData.getInstance();
        
        for (var i = 0; i < this.MAX_PLAYER; i++) 
        {
            if (this["player" + i].data) 
            {
                this.gameEffectPanel.showGameEndScoreResultEffect(this["player" + i]);
            }
        }
        this.gameEffectPanel.moveGoldToBanker(egret.getDefinitionByName("goldFly" + this.bankerSeat), this.lGameScore);
    }

    public gameEndInitView():void
    {
        this.initGameView();
        egret.Tween.removeTweens(this.gameEffectPanel);
        egret.Tween.removeTweens(this);
        this.gameEffectPanel.cleanGameOverEffects();
        this.gameEffectPanel.cleanGoldEffects();
        this.gameEffectPanel.cleanGameAnimations();
        this.gameEffectPanel.cleaneffectCards();
        this.effectPlayers = [];
    }

    //玩家摊牌
    public showPlayerCard(playerIndex: number, data: any): void 
    {
        this["wancheng" + playerIndex].visible = false;
        var cbCardData = NNCardLogic.SortByCards(data.cbCardData);
        var playerCards = this["playerCards" + playerIndex];
        if (playerCards.animator) 
        {
            playerCards.removeChild(playerCards.animator);
            playerCards.animator = null;
        }
        var animator: how.Animator = new how.Animator();
        animator.source = "nn_fanpai";
        animator.defentAnimationName = "nn_fanpai";
        animator.sourceGroup = "niuniu_effect";
        animator.playOnce = true;
        animator.verticalCenter = playerCards.verticalCenter;
        animator.horizontalCenter = playerCards.horizontalCenter;
        this.addChild(animator);
        animator.addHander((playerCards, animator, cbCardData) => {
            this.removeChild(animator);
            //显示玩家的牌
            for (var i = 0; i < cbCardData.length; i++) 
            {
                var card: eui.Image = this["p" + playerIndex + "card" + i];
                if (i < 3) 
                {
                    card.x = card.x - 20;
                }
                card.visible = true;
                card.source = "card_" + cbCardData[i] + "_png";
            }
            var animatorCardType: how.Animator = new how.Animator();
            animatorCardType.source = "nntype" + data.CardType;
            animatorCardType.defentAnimationName = "newAnimation";
            animatorCardType.sourceGroup = "niuniu_effect";
            animatorCardType.playOnce = true;
            animatorCardType.bottom = 25;
            animatorCardType.horizontalCenter = -5;
            playerCards.addChild(animatorCardType);
            playerCards.animator = animatorCardType;
            if (playerIndex == 0)
            {
                //如果是自己
                this.gameEffectPanel.playGameAnimation("nn_myCardType" + data.CardType + "_{0}_png", this.nn_myCardType[data.CardType], true);
            }
        }, this, [playerCards, animator, cbCardData]);
        how.SoundManager.playEffect(data.mp3Source);
    }

    //用户摊牌
    public openCard(data: any): void 
    {
        var seatId = this.c2p(data.wPlayerChairID);
        if (this["player" + seatId].data) 
        {
            var gender = this["player" + seatId].data.gender == 1 ? "malecow_" : "femalecow_";
            data.mp3Source = gender + data.CardType + "_mp3";
            this["player" + seatId].openCardData = data;
            if (!AppData.getInstance().isGameHide) 
            {
                // this.callUI("pingCardComplete", seatId);
                this.pingCardComplete(seatId);
            }
        }
    }

    

    //开始倒计时
    public startProgressTimer(time = 10): void
    {
        egret.Tween.removeTweens(this.progressTimerLabel);
        if (time < 0) 
        {
            return;
        }
        this.progressTimerLabel.text = time.toString();
        this.progressTimerLabel.alpha = 1;
        this.progressTimerGroup.visible = true;
        time--;
        if (time == 0) 
        {
            this.progressTimerGroup.visible = false;
        } 
        else 
        {
            this.progressTimerLabel.text = time.toString();
            egret.Tween.get(this.progressTimerLabel).wait(900).to({ alpha: 0 }, 100).call(this.startProgressTimer, this, [time]);
        }
    }

    public initGameView(): void 
    {
        this.operateCardGroup.visible = false;
        this.progressTimerGroup.visible = false;
        this.tipImg.visible = false;
        this.cardTypeGroup.visible = false;
        var flag = this.playerCardsXList.length == 0;
        
        for (var i = 0; i < 5; i++)
        {
            this["card" + i].visible = false;
            this["addScoreBtnGroup0"].visible = false;
            if (i <= 3) 
            {
                var list = [];
                for (var j = 0; j < 5; j++) 
                {
                    var card: eui.Image = this["p" + i + "card" + j];
                    if (flag) 
                    {
                        list.push(card.x);
                    } 
                    else 
                    {
                        card.x = this.playerCardsXList[i][j];
                    }
                    card.visible = false;
                }
                if (list.length > 0) 
                {
                    this.playerCardsXList.push(list);
                }
                var playerCards = this["playerCards" + i];
                if (playerCards.animator) 
                {
                    playerCards.removeChild(playerCards.animator);
                    playerCards.animator = null;
                }
                this["fightCardLabel" + i].text = "";
                this["myScoreAreaLabelGroup" + i].visible = false;
                this["wancheng" + i].visible = false;
            }
        }

        //自己拼牌列表归位
        for (var i = 0; i < this.onCardList.length; i++) 
        {
            var ta = this.onCardList[i];
            ta.y = ta.y + 20;
            ta["fightCardLabel"] = null;
        }
        this.onCardList = [];
        this.onCardListCount = 0;
    }

     //收到开始加注
    public startAddScore(data: any): void 
    {
        console.log(">>> NNGameSceneView startAddScore this.bankerSeat:" + this.bankerSeat);
        this.tipImg.visible = this.bankerSeat == 0;
        if (this.bankerSeat == 0)
        {
            this.changeNNTips(1);
        } 
        else 
        {
            this["p0addScoreBtnBg"].visible = true;
            this["addScoreBtnGroup0"].visible = true;
            this["p0addScoreBtn" + 0].visible = true;
            this["p0addScoreBtn" + 1].visible = true;
            this["p0addScoreBtn" + 2].visible = true;
            this["p0addScoreBtn" + 0]["bitLabel"].text = "2倍";
            this["p0addScoreBtn" + 1]["bitLabel"].text = "3倍";
            this["p0addScoreBtn" + 2]["bitLabel"].text = "5倍";
        }
    }

    
        //显示呼吸灯动画
    public showBreatheLight(): void 
    {
        egret.Tween.get(this.nn_deng, { loop: true }).to({ alpha: 0 }, 2000).to({ alpha: 1 }, 2000);
    }

        //按下返回按钮
    public onBackButton(): void 
    {
        this.backMenuGroup.visible = false;
        if(this.playerList[0].isPlay())
        {
            this.alert = how.Alert.show(LanguageConfig.onBackButtonPlayerisGaming, () =>
            {
                this.alert = null;
            });
        }
        else
        {
            this.dailog = how.Dialog.show(LanguageConfig.onBackButtonTip, this.sendBack, function ()
            {
                this.dailog = null;
            }, this);
        }
    }

    //发送返回消息
    public sendBack(): void 
    {
        this.dailog = null;
        // this.communicate(LoaddingGlobalModule.response.showLoad);
        // this.isBackstatus = BackStatusConfig.back;
        // this.clickQuitFlag = true;
        WebSocketInstance.getHallSocket().send(CMDConfig.SEND_LEAVE_GAME, {});
        WebSocketInstance.getHallSocket().send(CMDConfig.SEND_LEAVE_ROOM, {});
    }

    //点击背景区域
    public onTouchGroup(): void 
    {
        this.backMenuGroup.visible = false;
        this.cardTypeGroup.visible = false;
    }

    //按下设置按钮
    private onSettingBtn(): void 
    {
        this.backMenuGroup.visible = false;
        // this.report(NNGameSceneModule.request.onSettingBtn);
        how.SettingWindow.show();

    }

    //按下菜单按钮
    public onMenuButton(): void 
    {
        this.backMenuGroup.visible = !this.backMenuGroup.visible;
        this.cardTypeGroup.visible = false;
    }

    //按下配型倍数按钮
    private onCardTypeButton() 
    {
        this.backMenuGroup.visible = false;
        this.cardTypeGroup.visible = true;
    }

    //点击有牛按钮
    public onYouniuBtn(): void 
    {
        var cardType = NNCardLogic.getCardType(this.cbCardData);
        if (this.onCardList.length < 3) 
        {
            how.SoundManager.playEffect("nn_montageerror_mp3");
            this.pinpaicuowu.visible = true;
            this.pinpaicuowu.play();
            return;
        }
        if (cardType > 10) 
        {
            this.pingCardComplete(0);
            how.SoundManager.playEffect("nn_carddone_mp3");
            // this.report(NNGameSceneModule.request.onYouniuBtn, cardType);
            WebSocketInstance.getHallSocket().send(CMDConfig.SEND_COMPARECARD, { bOX: 1 });

            return;
        }
        if (this.onCardList.length == 3 && this.onCardListCount % 10 == 0) 
        {
            this.pingCardComplete(0);
            how.SoundManager.playEffect("nn_carddone_mp3");
            // this.report(NNGameSceneModule.request.onYouniuBtn, cardType);
            WebSocketInstance.getHallSocket().send(CMDConfig.SEND_COMPARECARD, { bOX: 1 });
        } 
        else 
        {
            how.SoundManager.playEffect("nn_montageerror_mp3");
            this.pinpaicuowu.visible = true;
            this.pinpaicuowu.play();
        }
    }

     //玩家拼牌完成
    public pingCardComplete(playerIndex: number): void 
    {
        if (playerIndex == 0) 
        {
            for (var i = 0; i < 5; i++) 
            {
                var card: eui.Image = this["p" + playerIndex + "card" + i];
                card.visible = true;
                card.source = "card_0_png";
            }
            this.tipImg.visible = true;
            this.tipImg.source = "nn_tip2_png";
            this.operateCardGroup.visible = false;
            this.tip2Group.visible = false;
        } 
        else 
        {
            how.SoundManager.playEffect("nn_carddone1_mp3");
        }
        for (var j = 0; j < 5; j++) 
        {
            var card: eui.Image = this["p" + playerIndex + "card" + j];
            card.visible = true;
            card.source = "card_0_png";
        }
        this["wancheng" + playerIndex].visible = true;
    }


    //点击没牛按钮
    public onMeiniuBtn(): void 
    {
        var cardType = NNCardLogic.getCardType(this.cbCardData)
        if (cardType > 0) 
        {
            how.SoundManager.playEffect("nn_montageerror_mp3");
            this.pinpaicuowu.visible = true;
            this.pinpaicuowu.play();
        } 
        else 
        {
            // this.report(NNGameSceneModule.request.onMeiniuBtn);
            WebSocketInstance.getHallSocket().send(CMDConfig.SEND_COMPARECARD, { bOX: 0 });

            this.pingCardComplete(0);
            how.SoundManager.playEffect("nn_carddone_mp3");
        }
    }

    //点击扑克牌
    public onCard(event: egret.TouchEvent): void 
    {
        var ta: how.Button = event.currentTarget;
        var index = this.onCardList.indexOf(ta);
        if (index != -1) 
        {
            ta.y = ta.y + 20;
            this.onCardList.splice(index, 1);
        } 
        else if (this.onCardList.length < 3) 
        {
            ta.y = ta.y - 20;
            this.onCardList.push(ta);
        }
        this.onCardListCount = 0;
        for (var i = 0; i < this.onCardList.length; i++) 
        {
            var cardValue = NNCardLogic.getNNCardValue(this.cbCardData, parseInt(this.onCardList[i].name));
            this.onCardListCount += cardValue;
            this["fightCardLabel" + i].text = cardValue;
        }
        for (var i = this.onCardList.length; i < 3; i++) 
        {
            this["fightCardLabel" + i].text = "";
        }
        this.fightCardLabel3.text = this.onCardList.length != 0 ? this.onCardListCount.toString() : "";
        how.SoundManager.playEffect("nn_dealcard_mp3");
    }

    //按下游戏记录按钮
    public onGameRecord(): void 
    {
        this.backMenuGroup.visible = false;
        // this.report("onGameRecord");
    }

        //按下帮助按钮
    public onHelpButton(): void 
    {
        this.backMenuGroup.visible = false;
        // this.report("onHelpButton");
    }

    //按下知道了按钮
    public onZhidaoBtn(): void 
    {
        var storageData = base.Utils.getLocalStorageItem(StorageKeys.nnTip, "Object");
        storageData.tip0 = true;
        this.tip0Group.visible = false;
        egret.localStorage.setItem(StorageKeys.nnTip, JSON.stringify(storageData));
    }

    //按下加注区域按钮
    public onAddScoreAreaBtn(event: egret.TouchEvent): void 
    {
        var ta: how.Button = event.currentTarget;
        var score = parseInt(ta.name.substring(3, 4));
        
        this["p0addScoreBtn" + 0].visible = false;
        this["p0addScoreBtn" + 1].visible = false;
        this["p0addScoreBtn" + 2].visible = false;
        this["p0addScoreBtnBg"].visible = false;

        // this.report(NNGameSceneModule.request.onAddScoreAreaBtn, score);

        WebSocketInstance.getHallSocket().send(CMDConfig.SEND_QIPAi, {lScore : score});
    }

    //显示自己的牌
    public showMyCard(cbCardData: any, isEffect: boolean): void 
    {
        this.changeNNTips(1);
        for (var j = 0; j < 5; j++) 
        {
            this["p0card" + j].visible = false;
            if (!isEffect) 
            {
                this["card" + j].visible = true;
                this["card" + j].source = "card_" + cbCardData[j] + "_png";
            }
        }
        this["addScoreBtnGroup0"].visible = false;
        this.cbCardData = cbCardData;
        this.tipImg.visible = false;
        this.operateCardGroup.visible = true;
    }

    // 切换提示文字状态
    public changeNNTips(tips: Number)
    {
        switch(tips)
        {
            case 0:
            case 1:
            case 2:
                this.tipImg.source = "nn_tip" + tips + "_png";
                console.log(">>> changeNNTips source:" + this.tipImg.source);
                this.tipImg.visible = true;
                break;
            default:
                this.tipImg.visible = false;
                break;
        }
    }
}